
package com.gw.business.analysis.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.google.common.collect.Maps;
import com.gw.business.analysis.model.UserTrackDataAttribution;
import com.gw.business.analysis.model.UserTrackDataDetail;
import com.gw.business.analysis.model.UserTrackDataStatistics;
import com.gw.business.analysis.service.UserTrackDataDetailService;
import com.gw.business.statistics.detailed.model.DetailForm;
import com.gw.platform.page.impl.Page;
import com.gw.platform.service.impl.DefaultService;
import com.gw.platform.util.DateUtils;
import com.gw.platform.util.StringUtils;

@Service
public class UserTrackDataDetailServiceImpl extends DefaultService implements UserTrackDataDetailService {
    
    @Override
    public Boolean insert(UserTrackDataDetail item) {
        try {
            this.insert("UserTrackDataDetail_inset", item);
        } catch (Exception e) {
            return false;
        }
        return true;
    }
    
    @Override
    public Boolean update(UserTrackDataDetail item) {
        try {
            this.update("UserTrackDataDetail_update", item);
        } catch (Exception e) {
            return false;
        }
        return true;
    }
    
    @Override
    public List<UserTrackDataDetail> findEndTimeBigUser(String endTime) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("endTime", endTime);
        return (List<UserTrackDataDetail>) this.find("UserTrackDataDetail_findEndTimeBigUser", map);
    }
    
    /**
     * 获取详情列表
     */
    public Page queryUserList(DetailForm form, String pageNum, String pageSize) {
        int iPageNum = 1;
        int iPageSize = 20;
        if (pageNum != null) {
            iPageNum = Integer.valueOf(pageNum);
            iPageSize = Integer.valueOf(pageSize);
        }
        // 查询条件处理，若有快速查询条件，则只根据快速查询条件查询
        Map<String, Object> param = Maps.newHashMap();
        
        // 行为
        if (!StringUtils.isEmpty(form.getBehaviorType())){
            if(form.getBehaviorType().equals("1")||form.getBehaviorType().equals("2")){
                if(form.getBehaviorType().equals("1")){
                    param.put("beyTemp","true");
                }
            param.put("behaviorType", form.getBehaviorType());
            }else {
                //模拟开户
                if(form.getBehaviorType().equals("3")){
                    param.put("behaviorDetailType", "D");
                }else if (form.getBehaviorType().equals("4")){
                    param.put("behaviorDetailType", "N");
                }else if(form.getBehaviorType().equals("5")){
                    param.put("behaviorDetailType", "R");
                }
            }
        }
        // 来源
        if (!StringUtils.isEmpty(form.getUtmcsr()))
            param.put("utmCsrs", form.getUtmcsr());
        // 媒介
        if (!StringUtils.isEmpty(form.getUtmcmd()))
            param.put("utmCmds", form.getUtmcmd());
        // 用户
        if (!StringUtils.isEmpty(form.getUserId()))
            param.put("userId", form.getUserId());
        // 系列
        if (!StringUtils.isEmpty(form.getUtmccn()))
            param.put("utmCcns", form.getUtmccn());
        // 组
        if (!StringUtils.isEmpty(form.getUtmcct()))
            param.put("utmCcts", form.getUtmcct());
        // 关键词
        if (!StringUtils.isEmpty(form.getMarkWords()))
            param.put("markWords", form.getMarkWords());
        //开始时间
        if (!StringUtils.isEmpty(form.getStartTime()))
            
            param.put("startTime", DateUtils.stringToDate(form.getStartTime(),"yyyy-MM-dd HH:mm:ss"));
        //结束时间
        if (!StringUtils.isEmpty(form.getEndTime()))
            param.put("endTime", DateUtils.stringToDate(form.getEndTime(),"yyyy-MM-dd HH:mm:ss"));
        
        if (!StringUtils.isEmpty(form.getBeginTime())) {
            
            param.put("beginTime", form.getBeginTime());
        }
        // 结束时间
        if (!StringUtils.isEmpty(form.getEnTime())) {
            param.put("enTime", form.getEnTime());
        }
        if(!StringUtils.isEmpty(form.getRegistException())){
            param.put("exception",form.getRegistException() );
        }
        return super.page("queryDetailList", "queryDetailCount", iPageNum, param, iPageSize);
    }

    /**
     * 获取注册异常信息
     * @param startTime
     * @param endTime
     * @param isSend
     * @return
     */
    public List<UserTrackDataDetail> queryRegistExceptionData(String startTime, String endTime, String isSend) {
        // 查询条件处理，若有快速查询条件，则只根据快速查询条件查询
        Map<String, Object> param = Maps.newHashMap();
        //开始时间
        if (!StringUtils.isEmpty(startTime))
            
            param.put("startTime", startTime);
        //结束时间
        if (!StringUtils.isEmpty( endTime)){
            param.put("endTime", endTime);
        }
        //发送状态
        if (!StringUtils.isEmpty( isSend)){
            param.put("isSend", isSend);
        }
        return (List<UserTrackDataDetail>)this.find("queryUserRegistExceptionList", param);
    }
   
   

    /**
     * 获取当天有没有发送注册异常邮件
     * @param nowTime
     * @param userId
     * @return
     */
    public List<UserTrackDataDetail> queryRegistExceptionSendData(String nowTime, String userId) {
        // 查询条件处理，若有快速查询条件，则只根据快速查询条件查询
        Map<String, Object> param = Maps.newHashMap();
        //时间
        if (!StringUtils.isEmpty(nowTime))
            
            param.put("nowTime", nowTime);
        
        //发送状态
        if (!StringUtils.isEmpty(userId)){
            param.put("userId", userId);
        }
        return (List<UserTrackDataDetail>)this.find("getUserRegistExceptionSend", param);  
    }  
	@Override
	public List<UserTrackDataStatistics> groupByhourDate(
			String startTime) {
			Map<String, Object> map = new HashMap<String, Object>();
	        map.put("startTime", startTime);
	        
	        Map<String,UserTrackDataStatistics>   endMap = new HashMap<String, UserTrackDataStatistics>();
	     
	        List<UserTrackDataStatistics> result = new ArrayList<UserTrackDataStatistics>();
	        
	        //访问次数
	        result = (List<UserTrackDataStatistics>) this.find("UserTrackDataDetail_groupByhourDate_visitCount", map);
	        endMap = setDataCount(endMap, result);
	        //资讯次数
	        result = (List<UserTrackDataStatistics>) this.find("UserTrackDataDetail_groupByhourDate_advisoryCount", map);
	        endMap = setDataCount(endMap, result);
	        
	        
	        //模拟开户次数
	        result = (List<UserTrackDataStatistics>) this.find("UserTrackDataDetail_groupByhourDate_demoCount", map);
	        for (UserTrackDataStatistics userTrackDataStatistics : result) {
				String str = userTrackDataStatistics.getBehaviorDetailType();
				int index = 0;
				if(!str.equals("")){
					String strs[] = str.split(",");
					for (int i = 0; i < strs.length; i++) {
						String s = strs[i];
						if(s.indexOf("D") == 0){
							index ++;
						}
					}
				}
				userTrackDataStatistics.setDemoCount(index);
			}
	        endMap = setDataCount(endMap, result);
	        //真实开户次数
	        result = (List<UserTrackDataStatistics>) this.find("UserTrackDataDetail_groupByhourDate_realCount", map);
	        for (UserTrackDataStatistics userTrackDataStatistics : result) {
				String str = userTrackDataStatistics.getBehaviorDetailType();
				int index = 0;
				if(!str.equals("")){
					String strs[] = str.split(",");
					for (int i = 0; i < strs.length; i++) {
						String s = strs[i];
						if(s.indexOf("N") == 0){
							index ++;
						}
					}
				}
				userTrackDataStatistics.setRealCount(index);
			}
	        endMap = setDataCount(endMap, result);
	        //入金次数
	        result = (List<UserTrackDataStatistics>) this.find("UserTrackDataDetail_groupByhourDate_depositCount", map);
	        for (UserTrackDataStatistics userTrackDataStatistics : result) {
				String str = userTrackDataStatistics.getBehaviorDetailType();
				int index = 0;
				if(!str.equals("")){
					String strs[] = str.split(",");
					for (int i = 0; i < strs.length; i++) {
						String s = strs[i];
						if(s.indexOf("R") == 0){
							index ++;
						}
					}
				}
				userTrackDataStatistics.setDepositCount(index);
			}
	        endMap = setDataCount(endMap, result);
	        
	       
	        List<UserTrackDataStatistics> endResult = new ArrayList<UserTrackDataStatistics>();
	        Iterator<String> insertObjKeys= endMap.keySet().iterator();
			while (insertObjKeys.hasNext()) {
				String key=insertObjKeys.next();
				endResult.add(endMap.get(key));
			}
			
	        return endResult;
	}
	
	
	
	private Map<String,UserTrackDataStatistics> setDataCount(Map<String,UserTrackDataStatistics> endMap,List<UserTrackDataStatistics> result){
		
		for (UserTrackDataStatistics userTrackDataStatistics : result) {
			String key = userTrackDataStatistics.getFormatDataTime() +"_"+userTrackDataStatistics.getHours()+"_"+userTrackDataStatistics.getUtmcsr()+"_"+userTrackDataStatistics.getUtmcmd();
			
			UserTrackDataStatistics obj = endMap.get(key);
			if(obj == null){
				endMap.put(key, userTrackDataStatistics);
			}else{
				obj.setAdvisoryCount(obj.getAdvisoryCount() + userTrackDataStatistics.getAdvisoryCount());
				
				obj.setRealCount(obj.getRealCount() + userTrackDataStatistics.getRealCount());
				
				obj.setDemoCount(obj.getDemoCount() + userTrackDataStatistics.getDemoCount());
				
				obj.setDepositCount(obj.getDepositCount() + userTrackDataStatistics.getDepositCount());
				
				obj.setVisitCount(obj.getVisitCount() + userTrackDataStatistics.getVisitCount());
			}
		}
		return endMap;
		
	}
	
	/**
     * 修改用户注册异常为已邮件发送
     * @param userId
     * @param time
     */
    public void updateUserRegistExceptionSend(String userId,String time){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("nowTime", time);
        map.put("userId", userId);
        this.update("updateUserRegistExceptionSend",map);
    }
    
    /**
     * 归因开始
     * @param visitTimeBeign
     * @param visitTimeEnd
     */
    @Override
	public List<UserTrackDataDetail> getBaseSourceByDataTime(String userId,String visitTimeBeign,String visitTimeEnd) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId", userId);
		map.put("visitTimeBeign", visitTimeBeign);
		map.put("visitTimeEnd", visitTimeEnd);
		return (List<UserTrackDataDetail>) this.find("getBaseSourceByDataTime", map);
	}

	@Override
	public List<UserTrackDataDetail> getVisitFirstData(String userId,
			String utmcsr, String utmcmd, String visitTime) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId", userId);
		map.put("utmcsr", utmcsr);
		map.put("utmcmd", utmcmd);
		map.put("visitTime", visitTime);
		return (List<UserTrackDataDetail>) this.find("UserTrackBasic_First", map);
	}

	@Override
	public List<UserTrackDataDetail> getBaseSourceByDataTimeExpert(String behaviorDetailType,
			String visitTimeBeign, String visitTimeEnd,String mark) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("behaviorDetailType", behaviorDetailType);
		map.put("visitTimeBeign", visitTimeBeign);
		map.put("visitTimeEnd", visitTimeEnd);
		map.put("mark", mark);
		return (List<UserTrackDataDetail>) this.find("getBaseSourceByDataTimeExpert", map);
	}
	
	@Override
	public boolean updateObjTrack(UserTrackDataDetail obj) {
		 try {
			 defaultDao.update("UserTrackDataDetail_update_Track", obj);
	        } catch (Exception e) {
	            return false;
	        }
	        return true;
	}



    /**
     * 获取指定某天的所有模拟开户或真实开户的详细会话数据
     * @param visitTime 访问时间，格式为 yyyy-MM-dd
     * @return
     */
    public List<UserTrackDataDetail> queryDataDetailByDay(String visitTime){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("visitTime", visitTime);
        return (List<UserTrackDataDetail>) this.find("queryDataDetailByDay", map);
    }


    /**
     * 根据用户id 获取该用户的第一次访问数据
     * @param userId 用户ID
     * @return
     */
    public UserTrackDataDetail getVisitFirstData(String userId){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", userId);
        List<UserTrackDataDetail> list = (List<UserTrackDataDetail>) this.find("UserTrackBasic_First", map);
        if(list == null || list.size() == 0)
            return  null;
        return list.get(0);
    }


    /**
     * 根据用户id 获取用户在结束时间之前的第一次模拟开户
     * @param userId 用户ID
     *  @param endTime 结束时间
     * @return
     */
    public UserTrackDataDetail getFirstDemoDataDetail(String userId,String endTime){
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userId", userId);
        map.put("endTime", endTime);
        List<UserTrackDataDetail> list = (List<UserTrackDataDetail>) this.find("getAllDemoDataDetailByUserId", map);
        if(list == null || list.size() == 0)
            return  null;
        return list.get(0);
    }


    @Override
    public void batchUpdate(List<Integer> list){
        if(list != null && list.size() > 0)
            this.defaultDao.update("UserTrackDataDetail.batchUpdateDetail", list);
    }

}
